<?php
class Model_TableAdresse implements Model_ITable
{
	private static $con = null;
	private static $reqSelectAll = null;
	private static $reqSelectOne = null;
	private static $reqInsert = null;
	private static $reqDeleteOne = null;
	private static $reqUpdate = null;
	
	public static function setConnexion(MyPdo $pdo)
	{
		self::$con = $pdo;
	}
	
	public static function getConnexion()
	{
		return self::$con;
	}

	public static function init()
	{
		self::$reqSelectAll = self::$con->prepare('SELECT * FROM adresse ORDER BY id_adresse');
		self::$reqSelectOne = self::$con->prepare('SELECT * FROM adresse WHERE id_adresse = :idcond');
		self::$reqDeleteOne = self::$con->prepare('DELETE FROM adresse WHERE id_adresse = :idcond');
		self::$reqInsert = self::$con->prepare('INSERT INTO adresse(adresse1, adresse2, id_commune) VALUES(:adresse1, :adresse2, :idcommune)');
		self::$reqUpdate = self::$con->prepare('UPDATE adresse SET adresse1 = :adresse1, adresse2 = :adresse2, id_commune = :idcommune WHERE id_adresse = :idcond');
	}

	public static function fetchAll()
	{
		self::$reqSelectAll->execute();
		$results = self::$reqSelectAll->fetchAll();
		return $results;
	}

	public static function fetchOne($id)
	{
		self::$reqSelectOne->execute(array(':idcond' => $id));
		$results = self::$reqSelectOne->fetchAll();
		if( empty($results[0]) )
			return array();
		else
			return $results[0];
	}
	
	public static function delete($id)
	{
		self::$reqDeleteOne->execute(array(':idcond' => $id));
	}
	
	public static function insert($adresse1, $adresse2, $idcommune)
	{
		self::$reqInsert->execute(array(
			':adresse1' => $adresse1,
			':adresse2' => $adresse2,
			':idcommune' => $idcommune
		));
		return self::$con->lastInsertId();
	}
	
	public static function update($id, $adresse1, $adresse2, $idcommune)
	{
		self::$reqUpdate->execute(array(
			':adresse1' => $adresse1,
			':adresse2' => $adresse2,
			':idcommune' => $idcommune,
			':idcond' => $id
		));
	}
}
